using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;

namespace CS490_Capstone___Stubby.Page
{
    public partial class LogIn : System.Web.UI.Page
    {
        WebServiceApplication.WebService webservice = new WebServiceApplication.WebService();
        String redirectHeight = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            
            String browserHeight;
            int contentHeight;

            // read screen height passed through URL
            if (Request.QueryString.ToString() != "")
            {
                HtmlGenericControl searchBody = (HtmlGenericControl)Page.Master.FindControl("myBody");
                // displays the appropriate header menu
                searchBody.Attributes.Add("onload", "showJavaScriptHeader();");

                // sets browser height to the visible browser height as passed by the query string
                // sets browser height to minimum of 550px if browser height is smaller
                browserHeight = (int.Parse(Request.QueryString["height"].ToString()) > 550) 
                    ? Request.QueryString["height"].ToString() : "550";

                // adds height attribute to redirectHeight
                redirectHeight = "?height=" + Request.QueryString["height"].ToString();
            }
            else
            {
                // sets browser height to default 800px if browser height cannot be determined
                browserHeight = "800";
            }

            // calculate and set the size of the input panel to fill the screen
            content.Height = contentHeight = int.Parse(browserHeight) - 120;
            topSpacer.Height = ((contentHeight - 220) / 2) - 15 > 0 ? ((contentHeight - 220) / 2) - 15 : 0;
        }

        private bool validInput()
        {
            // char array to test input against
            char[] badName = "*&#()[]{}%$@<>?/\\~`=!^|\":;".ToCharArray();
            char[] badPassword = "*?".ToCharArray();

            // change background color of all fields white
            userName.BackColor = System.Drawing.Color.White;
            password.BackColor = System.Drawing.Color.White;

            // checks to see if fields are invalid/incomplete
            if (userName.Text == "" || userName.Text.IndexOfAny(badName) >= 0)
            {
                userName.Text = "";
                userName.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201"); ;
            }
            if (password.Text == "" || password.Text.IndexOfAny(badPassword) >= 0)
            {
                password.Text = "";
                password.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201"); ;
            }

            if (userName.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                password.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")))
            // invalid/incomplete input detected
            {
                return false;
            }
            // no invalid/incomplete input detected
            else
            {
                return true;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!validInput())
            {
                // do nothing other than highlight which fields are incomplete or invalid
            }
            else
            // beginning of the valid input block -- do what the button is supposed to do
            {
                //For when a user logs in, checks to see if admin or user
                if (adminStatus.Checked)
                {
                    try
                    {
                        if (webservice.getSession(Session["AdminUserName"].ToString()) == Session.SessionID)
                        {
                            // If the session ID's match, the user is already logged in.
                            labelPrompt.Text = "You are already logged in.";
                            labelPrompt.Visible = true;
                            return;
                        }
                    }
                    catch (NullReferenceException) { }
                    if (webservice.loginAsAdministrator(userName.Text, password.Text) == 0)
                    {
                        webservice.insertAdminSession(userName.Text, Session.SessionID);
                        Session.Add("AdminUserName", userName.Text);
                        try
                        {
                            Response.Redirect(Session["autoRedirect"].ToString() + redirectHeight);
                        }
                        catch (NullReferenceException)
                        {
                            Response.Redirect("Administrator.aspx" + redirectHeight);
                        }
                    }
                    else
                    {
                        labelPrompt.Text = "Invalid credentials. Please log in again.";
                        labelPrompt.Visible = true;
                    }
                }
                else
                {
                    try
                    {
                        if (webservice.getSession(Session["userName"].ToString()) == Session.SessionID)
                        {
                            // If the session ID's match, the user is already logged in.
                            labelPrompt.Text = "You are already logged in.";
                            labelPrompt.Visible = true;
                            return;
                        }
                    }
                    catch (NullReferenceException) { }

                    if (webservice.loginAsUser(userName.Text, password.Text) == 0)
                    {
                        // create a session variable for a _User object to be used by Account.aspx
                        try
                         {
                             Session["loggedInUser"] = webservice.getSearchedUser(userName.Text);
                         }
                         catch (NullReferenceException) 
                         { 
                              Session.Remove("loggedInUser");
                              Session.Add("loggedInUser", webservice.getSearchedUser(userName.Text));
                              Session["loggedInUser"] = webservice.getSearchedUser(userName.Text);
                         }

                        webservice.insertSession(userName.Text, Session.SessionID);
                        Session.Add("userName", userName.Text);
                        try
                        {
                            Response.Redirect(Session["autoRedirect"].ToString() + redirectHeight);
                        }
                        catch (NullReferenceException)
                        {
                            Response.Redirect("Account.aspx" + redirectHeight);
                        }
                    }
                    else
                    {
                        labelPrompt.Text = "Invalid credentials. Please log in again.";
                        labelPrompt.Visible = true;
                    }
                }
            } // close of the valid input block
        }
    }
}